<?php
include('../../Redirect_modules.php');
unset($_SESSION['_REQUEST_vars']['subject_id']);
unset($_SESSION['_REQUEST_vars']['course_id']);
unset($_SESSION['_REQUEST_vars']['course_period_id']);


// if only one subject, select it automatically -- works for Course Setup and Choose a Course

foreach($_REQUEST['tables']['courses'][$_REQUEST['course_id']] as $in=>$dt)
{
    $_REQUEST['tables']['courses'][$_REQUEST['course_id']][$in]=str_replace("'","\'",$dt);
}
foreach($_REQUEST['tables']['course_periods'][$_REQUEST['cp_id']] as $in=>$dt)
{
    $_REQUEST['tables']['course_periods'][$_REQUEST['cp_id']][$in]=str_replace("'","\'",$dt);
}

#echo $_REQUEST['w_course_period_id'];
if($_REQUEST['course_period_id'] != 'new')
{
	if($_REQUEST['w_course_period_id'])
	{
		$sql_parent = "UPDATE course_periods SET PARENT_ID=".$_REQUEST['w_course_period_id']." WHERE COURSE_PERIOD_ID=".$_REQUEST['course_period_id'];
		DBQuery($sql_parent);
	} 
}

if($_REQUEST['modfunc']!='delete' && !$_REQUEST['subject_id'])
{
	$subjects_RET = DBGet(DBQuery("SELECT SUBJECT_ID,TITLE FROM course_subjects WHERE SCHOOL_ID='".UserSchool()."' AND SYEAR='".UserSyear()."'"));
	if(count($subjects_RET)==1)
		$_REQUEST['subject_id'] = $subjects_RET[1]['SUBJECT_ID'];
}

if(clean_param($_REQUEST['course_modfunc'],PARAM_ALPHAMOD)=='search')
{
	PopTable('header','Search');
	echo "<FORM name=F1 id=F1 action=Modules.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]&course_modfunc=search method=POST>";
	echo '<TABLE><TR><TD><INPUT type=text class=cell_floating name=search_term value="'.$_REQUEST['search_term'].'"></TD><TD><INPUT type=submit class=btn_medium value=Search onclick=\'formload_ajax("F1")\';></TD></TR></TABLE>';
	echo '</FORM>';
	PopTable('footer');

	if($_REQUEST['search_term'])
	{
		$subjects_RET = DBGet(DBQuery('SELECT SUBJECT_ID,TITLE FROM course_subjects WHERE (UPPER(TITLE) LIKE \'%'.strtoupper($_REQUEST['search_term']).'%\' OR UPPER(SHORT_NAME) = \''.strtoupper($_REQUEST['search_term']).'\') AND SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\''));
		$courses_RET = DBGet(DBQuery('SELECT SUBJECT_ID,COURSE_ID,TITLE FROM courses WHERE (UPPER(TITLE) LIKE \'%'.strtoupper($_REQUEST['search_term']).'%\' OR UPPER(SHORT_NAME) = \''.strtoupper($_REQUEST['search_term']).'\') AND SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\''));
		$periods_RET = DBGet(DBQuery('SELECT c.SUBJECT_ID,cp.COURSE_ID,cp.COURSE_PERIOD_ID,cp.TITLE FROM course_periods cp,courses c WHERE cp.COURSE_ID=c.COURSE_ID AND (UPPER(cp.TITLE) LIKE \'%'.strtoupper($_REQUEST['search_term']).'%\' OR UPPER(cp.SHORT_NAME) = \''.strtoupper($_REQUEST['search_term']).'\') AND cp.SYEAR=\''.UserSyear().'\' AND cp.SCHOOL_ID=\''.UserSchool().'\''));

		echo '<TABLE><TR><TD valign=top>';
		$link['TITLE']['link'] = "Modules.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]";
		$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID');
		ListOutput($subjects_RET,array('TITLE'=>'Field'),'Field','Fields',$link,array(),array('search'=>false,'save'=>false));
		echo '</TD><TD valign=top>';
		$link['TITLE']['link'] = "Modules.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]";
		$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID');
		ListOutput($courses_RET,array('TITLE'=>'Course'),'Course','Courses',$link,array(),array('search'=>false,'save'=>false));
		echo '</TD><TD valign=top>';
		$link['TITLE']['link'] = "Modules.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]";
		$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID','course_id'=>'COURSE_ID','course_period_id'=>'COURSE_PERIOD_ID');
		ListOutput($periods_RET,array('TITLE'=>'Course Period'),'Course Period','Course Periods',$link,array(),array('search'=>false,'save'=>false));
		echo '</TD></TR></TABLE>';
	}
}

// UPDATING
if(clean_param($_REQUEST['tables'],PARAM_NOTAGS) && ($_POST['tables'] || $_REQUEST['ajax']) && AllowEdit())
{
	$where = array('course_subjects'=>'SUBJECT_ID',
					'courses'=>'COURSE_ID',
					'course_periods'=>'COURSE_PERIOD_ID');

	if($_REQUEST['tables']['parent_id'])
		$_REQUEST['tables']['course_periods'][$_REQUEST['course_period_id']]['PARENT_ID'] = $_REQUEST['tables']['parent_id'];

	foreach($_REQUEST['tables'] as $table_name=>$tables)
	{
		foreach($tables as $id=>$columns)
		{
			if($columns['TOTAL_SEATS'] && !is_numeric($columns['TOTAL_SEATS']))
				$columns['TOTAL_SEATS'] = ereg_replace('[^0-9]+','',$columns['TOTAL_SEATS']);
			if($columns['DAYS'])
			{
                                                            foreach($columns['DAYS'] as $day=>$y)
                                                            {
                                                                    if($y=='Y')
                                                                            $days .= $day;
                                                            }
                                                            $columns['DAYS'] = $days;
			}

			if($columns['DAYS_PRACTICE'])
			{
                                                            foreach($columns['DAYS_PRACTICE'] as $day_practice=>$y)
                                                            {
                                                                    if($y=='Y')
                                                                            $days_practice .= $day_practice;
                                                            }
                                                            $columns['DAYS_PRACTICE'] = $days_practice;
			}
			
			
			
			if($id!='new')
			{
				if($table_name=='courses' && $columns['SUBJECT_ID'] && $columns['SUBJECT_ID']!=$_REQUEST['subject_id'])
					$_REQUEST['subject_id'] = $columns['SUBJECT_ID'];

				$sql = 'UPDATE '.$table_name.' SET ';

				if($table_name=='course_periods')
				{
                                      if(scheduleAssociation($id))
                                      {
                                          $scheduleAssociation=true;
                                      }
                                      if(gradeAssociation($id))
                                      {
                                          $gradeAssociation=true;
                                      }
					$current = DBGet(DBQuery('SELECT TEACHER_ID,PERIOD_ID,MARKING_PERIOD_ID,DAYS,DAYS_PRACTICE,SHORT_NAME,TOTAL_SEATS,FILLED_SEATS, ROOM, ROOM_PRACTICE FROM course_periods WHERE '.$where[$table_name].'=\''.$id.'\''));
                                                                                          if($scheduleAssociation)
                                                                                          {
                                                                                                $cur_total_seat=$current[1]['TOTAL_SEATS'];
                                                                                                $cur_filled_seat=$current[1]['FILLED_SEATS'];
                                                                                          }
                                                                                          if($columns['TEACHER_ID'])
						$staff_id = $columns['TEACHER_ID'];
					else
						$staff_id = $current[1]['TEACHER_ID'];
					if($columns['PERIOD_ID']){
						$period_id = $columns['PERIOD_ID'];
					}
					else{
						$period_id = $current[1]['PERIOD_ID'];;
					}
					if(isset($columns['MARKING_PERIOD_ID']))
						$marking_period_id = $columns['MARKING_PERIOD_ID'];
					else
						$marking_period_id = $current[1]['MARKING_PERIOD_ID'];
					if($columns['DAYS'])
						$days = $columns['DAYS'];
					else
						$days = $current[1]['DAYS'];
					if($columns['DAYS_PRACTICE'])
						$days_practice = $columns['DAYS_PRACTICE'];
					else
						$days_practice = $current[1]['DAYS_PRACTICE'];	
						
					if($columns['SHORT_NAME'])
						$short_name = $columns['SHORT_NAME'];
					else
						$short_name = $current[1]['SHORT_NAME'];

					if($columns['ROOM'])
						$room = $columns['ROOM'];
					else
						$room = $current[1]['ROOM'];
	
	
					if($columns['ROOM_PRACTICE'])
						$room_practice = $columns['ROOM_PRACTICE'];
					else
						$room_practice = $current[1]['ROOM_PRACTICE'];
	
	
					$teacher = DBGet(DBQuery('SELECT FIRST_NAME,LAST_NAME,MIDDLE_NAME FROM staff WHERE STAFF_ID=\''.$staff_id.'\''));
					$period = DBGet(DBQuery('SELECT TITLE FROM school_periods WHERE PERIOD_ID=\''.$period_id.'\' AND SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\''));
					//if(GetMP($marking_period_id,'TABLE')!='school_years')
						//$mp_title = GetMP($marking_period_id,'SHORT_NAME').' - ';
					//if(strlen($days)<5)
						//$mp_title .= $days.' - ';
						
					$mp_title = '';	
					if($short_name)
						$mp_title .= paramlib_validation($column=SHORT_NAME,$short_name).' - ';
					$title = str_replace("'","''",$mp_title.$teacher[1]['LAST_NAME'].' '.$teacher[1]['FIRST_NAME']);
					$sql .= 'TITLE=\''.$title.'\',';
					if(isset($columns['MARKING_PERIOD_ID']))
					{
						if(GetMP($columns['MARKING_PERIOD_ID'],'TABLE')=='school_years')
							$columns['MP'] = 'FY';
						elseif(GetMP($columns['MARKING_PERIOD_ID'],'TABLE')=='school_semesters')
							$columns['MP'] = 'SEM';
						else
							$columns['MP'] = 'QTR';
					}
				}
                                                                    if(!(isset($columns['TITLE']) && trim($columns['TITLE'])==''))
                                                                    {
																		/**********Start Edit Period_id Random into table COURSE_PERIOD**********/
																		$period_default = DBGet(DBQuery('SELECT * FROM school_periods WHERE SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\''));
																		if($period_default){
																			$columns['PERIOD_ID'] = $period_default[1]['PERIOD_ID'];		
																		}
																		/**********End Edit Period_id Random into table COURSE_PERIOD**********/
																		
                                                                        foreach($columns as $column=>$value)
                                                                        {
                                                                                if(($column=='TEACHER_ID') && $scheduleAssociation){
                                                                                    $asso_err[]='To Change teacher go to School Setup->Courses->Teacher Re-Assignment';
                                                                                    break 2;
                                                                                }
                                                                                if(($column=='PERIOD_ID') && $scheduleAssociation){
                                                                                    $asso_err[]='You can not edit Period because students are scheduled in it';
                                                                                    break 2;
                                                                                }
                                                                                elseif($column=='DAYS' && $scheduleAssociation){
                                                                                    $asso_err[]='You can not edit Days because students are scheduled in it';
                                                                                    break 2;
                                                                                }
																				elseif($column=='DAYS_PRACTICE' && $scheduleAssociation){
                                                                                    $asso_err[]='You can not edit Days_practice because students are scheduled in it';
                                                                                    break 2;
                                                                                }
                                                                                elseif($column=='MARKING_PERIOD_ID' && $scheduleAssociation){
                                                                                    $asso_err[]='You can not edit Marking Period because students are scheduled in it';
                                                                                    break 2;
                                                                                }
                                                                                elseif($column=='GRADE_SCALE_ID')
                                                                                {
                                                                                    if($columns['GRADE_SCALE_ID']!='' && $gradeAssociation)
                                                                                    {
                                                                                        $asso_err[]='You can not edit Grading Scale because final grading was done';
                                                                                        break 2;
                                                                                    }
                                                                                    if($columns['GRADE_SCALE_ID']=='')
                                                                                    {
                                                                                        $grd_scl=  DBGet(DBQuery('SELECT GRADE_SCALE_ID FROM course_periods WHERE course_period_id='.$id.''));
                                                                                        if($grd_scl[1]['GRADE_SCALE_ID']!='' && $gradeAssociation)
                                                                                        {
                                                                                            $asso_err[]='You can not edit Grading Scale because final grading was done';
                                                                                            break 2;
                                                                                        }
                                                                                    }
                                                                                }
                                                                                elseif($column=='CREDITS' && $gradeAssociation){
                                                                                    $asso_err[]='You can not edit Credits because final grading was done';
                                                                                    break 2;
                                                                                }
//                                                                                elseif($column=='TOTAL_SEATS' && isset($cur_total_seat) && $value<$cur_total_seat){
//                                                                                    $asso_err[]='You can not reduce Seats because it has association';
//                                                                                    break 2;
//                                                                                }
                                                                                elseif (isset ($columns['DOES_ATTENDANCE']) && $columns['DOES_ATTENDANCE']=='') 
                                                                                {
                                                                                    $attn=  DBGet(DBQuery('SELECT COUNT(*) AS TOTAL FROM attendance_period WHERE COURSE_PERIOD_ID='.$id.''));
                                                                                    if($attn[1]['TOTAL']>0)
                                                                                    {
                                                                                        $asso_err[]='You can not turn off take attendance as attendance has been taken for this course period.';
                                                                                        break 2;
                                                                                    }
                                                                                    else
                                                                                    {
                                                                                        DBQuery('DELETE FROM missing_attendance WHERE course_period_id='.$id.'');
                                                                                    }
                                                                                }
                                                                                elseif($column=='TOTAL_SEATS' && isset($cur_total_seat) && $value<$cur_filled_seat){
                                                                                    $asso_err[]='You can not reduce Seats because students are scheduled in it';
                                                                                    break 2;
                                                                                }
                                                                                elseif($column=='ROOM' && trim($value)==''){
                                                                                    break 2;
                                                                                }
                                                                                elseif($column=='SHORT_NAME' && trim($value)==''){
                                                                                    break 2;
                                                                                }
                                                                                $value=paramlib_validation($column,$value);
                                                                                if($column=='GRADE_SCALE_ID' && str_replace("\'","''",$value)==''){
                                                                                    $sql .= $column.' = NULL,';
                                                                                }
                                                                                else
                                                                                {
																					$go=true;	#$sql .= $column."='".str_replace("\'","''",$value)."',";
                                                                                    if(stripos($_SERVER['SERVER_SOFTWARE'], 'linux'))
                                                                                    {
                                                                                        $value =  mysql_real_escape_string($value);
                                                                                        $value=str_replace('%u201D', "\"", $value);
                                                                                    }
                                                                                    if(str_replace("\'","''",$value)=='')
                                                                                        $sql .= $column.' = NULL,';
                                                                                    else
                                                                                        $sql .= $column.'=\''.$value.'\',';
                                                                                }
                                                                        }
                                                                        $sql = substr($sql,0,-1) . ' WHERE '.$where[$table_name].'=\''.$id.'\'';
                                                                 
                                                                           if($go){
																		   //echo $sql;
                                                                           DBQuery($sql);
																		   }
                                                                        //UpdateMissingAttendance($id);
                                                                    }
				// ----------------------------------------------- //
				/*
				if($_REQUEST['w_course_period_id'])
				{
					
					$sql_1 = "UPDATE $table_name SET PARENT_ID=".$_REQUEST['w_course_period_id']." WHERE ".$where[$table_name]."='$id'";
					DBQuery($sql_1);
				} 
				*/
				// ----------------------------------------------- //
                                                                    

			}
			else
			{	
				$sql = 'INSERT INTO '.$table_name.' ';

				if($table_name=='course_subjects')
				{
					//$id = DBGet(DBQuery("SELECT ".db_seq_nextval('COURSE_SUBJECTS_SEQ').' AS ID'.FROM_DUAL));
                                                                                          $id = DBGet(DBQuery("SHOW TABLE STATUS LIKE 'course_subjects'"));
                                                                                          $id[1]['ID']= $id[1]['AUTO_INCREMENT'];
					$fields = 'SCHOOL_ID,SYEAR,';
					$values = '\''.UserSchool().'\',\''.UserSyear().'\',';
					$_REQUEST['subject_id'] = $id[1]['ID'];
				}
				elseif($table_name=='courses')
				{
					// $id = DBGet(DBQuery("SELECT ".db_seq_nextval('COURSES_SEQ').' AS ID'.FROM_DUAL));
                                          /* $id = DBGet(DBQuery("SELECT max(COURSE_ID) AS ID from courses"));
					$_REQUEST['course_id'] = $id[1]['ID']; */
                                                                                          $id = DBGet(DBQuery("SHOW TABLE STATUS LIKE 'courses'"));
                                                                                          $id[1]['ID']= $id[1]['AUTO_INCREMENT'];
                                                                                          $_REQUEST['course_id'] = $id[1]['ID'];
					$fields = 'SUBJECT_ID,SCHOOL_ID,SYEAR,';
					$values = '\''.$_REQUEST[subject_id].'\',\''.UserSchool().'\',\''.UserSyear().'\',';
				}

				elseif($table_name=='course_periods')
				{
                                                                                    //$id = DBGet(DBQuery("SELECT ".db_seq_nextval('COURSE_PERIODS_SEQ').' AS ID'.FROM_DUAL));
                                                                                    // edited at 4.11.2009 start
                                                                                    $id = DBGet(DBQuery('SHOW TABLE STATUS LIKE \'course_periods\''));
                                                                                    $id[1]['ID']= $id[1]['AUTO_INCREMENT'];
                                                                                    // edited at 4.11.2009 end
                                                                                    $fields = 'SYEAR,SCHOOL_ID,COURSE_ID,TITLE,';
                                                                                    $teacher = DBGet(DBQuery('SELECT FIRST_NAME,LAST_NAME,MIDDLE_NAME FROM staff WHERE STAFF_ID=\''.$columns[TEACHER_ID].'\''));
                                                                                    //$period = DBGet(DBQuery('SELECT TITLE FROM school_periods WHERE PERIOD_ID=\''.$columns[PERIOD_ID].'\' AND SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\''));

                                                                                    if(!isset($columns['PARENT_ID']))
                                                                                        $columns['PARENT_ID'] = $id[1]['ID'];

                                                                                    if(isset($columns['MARKING_PERIOD_ID']))
                                                                                    {
                                                                                        if(GetMP($columns['MARKING_PERIOD_ID'],'TABLE')=='school_years')
                                                                                            $columns['MP'] = 'FY';
                                                                                        elseif(GetMP($columns['MARKING_PERIOD_ID'],'TABLE')=='school_semesters')
                                                                                            $columns['MP'] = 'SEM';
                                                                                        else
                                                                                            $columns['MP'] = 'QTR';

                                                                                        if(GetMP($columns['MARKING_PERIOD_ID'],'TABLE')!='school_years')
                                                                                            $mp_title = GetMP($columns['MARKING_PERIOD_ID'],'SHORT_NAME').' - ';
                                                                                    }

                                                                                    /*if(strlen($columns['DAYS'])<5)
                                                                                    $mp_title .= $columns['DAYS'].' - ';
																					
																					if(strlen($columns['DAYS_PRACTICE'])<5)
                                                                                    $mp_title .= $columns['DAYS_PRACTICE'].' - ';
																					
																					
																					$mp_title .= $columns['GENDER_RESTRICTION'].' - ';
																					*/
																					$mp_title = '';
                                                                                    if($columns['SHORT_NAME'])
                                                                                        $mp_title .= paramlib_validation($column=SHORT_NAME,$columns['SHORT_NAME']).' - ';
                                                                                    
																					
																					$title = str_replace("'","''",$mp_title.$teacher[1]['LAST_NAME'].' '.$teacher[1]['FIRST_NAME']);
																				
                                                                                    $values = "'".UserSyear()."','".UserSchool()."','$_REQUEST[course_id]','$title',";
                                                                                    $_REQUEST['course_period_id'] = $id[1]['ID'];
				}
				
				$go = 0;
				foreach($columns as $column=>$value)
				{
                                                                                if($value!='')
                                                                                {
                                                                                        //echo "<BR>".$column."<BR>".$value;
                                                                                        $value=trim(paramlib_validation($column,$value));
                                                                                        $fields .= $column.',';
                                                                                        #$values .= "'".str_replace("\'","''",$value)."',";
                                                                                        if(stripos($_SERVER['SERVER_SOFTWARE'], 'linux'))
                                                                                        {
                                                                                            $value =  mysql_real_escape_string($value);
                                                                                        }
                                                                                        $values .= '"'.$value.'",';

                                                                                        $go = true;
                                                                                }
				}
				$sql .= '(' . substr($fields,0,-1) . ') values(' . substr($values,0,-1) . ')';

				if($go){
					//echo $sql;
					DBQuery($sql);
                                      
                }

				// ----------------------------------------------- //
				if($_REQUEST['w_course_period_id'])
				{
					$max_id = DBGet(DBQuery('SELECT MAX(COURSE_PERIOD_ID) AS CP_ID FROM course_periods;'));
					$sql_2 = 'UPDATE course_periods SET PARENT_ID='.$_REQUEST['w_course_period_id'].' WHERE COURSE_PERIOD_ID = '.$max_id[1]['CP_ID'];
					DBQuery($sql_2);
				}
				// ----------------------------------------------- //
				
			}
		}
                if(($scheduleAssociation || $gradeAssociation)&& is_array($asso_err)){
                                                                        foreach($asso_err as $err){
                                                                            ShowErrPhp($err);
                                                                        }
                                                                    }
	}
	unset($_REQUEST['tables']);
}

if(clean_param($_REQUEST['modfunc'],PARAM_ALPHAMOD)=='delete' && AllowEdit())
{
 	unset($sql);
        $course_period_id=paramlib_validation($colmn=PERIOD_ID,$_REQUEST[course_period_id]);
        $course_id=paramlib_validation($colmn=PERIOD_ID,$_REQUEST[course_id]);
        $subject_id=paramlib_validation($colmn=PERIOD_ID,$_REQUEST[subject_id]);
         
	if(clean_param($_REQUEST['course_period_id'],PARAM_ALPHANUM))
	{
			$table = 'course period';
			$sql[] = 'UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID=\''.$course_period_id.'\'';
			$sql[] = 'DELETE FROM course_periods WHERE COURSE_PERIOD_ID=\''.$course_period_id.'\'';
			$sql[] = 'DELETE FROM schedule WHERE COURSE_PERIOD_ID=\''.$course_period_id.'\'';
	}

	elseif(clean_param($_REQUEST['course_id'],PARAM_ALPHANUM))
	{
		$table = 'course';
			$course_period=DBGet(DBQuery('SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID=\''.$course_id.'\''));
			//print_r($course_period['COURSE_PERIOD_ID']);
			foreach($course_period as $course1)
			
			if($course1['COURSE_PERIOD_ID']=='') {
			//echo 'hiii';exit;
			$sql[] = 'DELETE FROM courses WHERE COURSE_ID=\''.$course_id.'\'';
			#$sql[] = "UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID IN (SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID='$_REQUEST[course_id]')";
			
                       ############# query error solved	##############	
			$extra_sql='SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID=\''.$course_id.'\'';
			$result_sql = DBGet(DBQuery($extra_sql));
			$sql[] = 'UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID = \''.$result_sql.'\'';
			

                        $sql[] = 'DELETE FROM course_periods WHERE COURSE_ID=\''.$course_id.'\'';
			$sql[] = 'DELETE FROM schedule WHERE COURSE_ID=\''.$course_id.'\'';
			$sql[] = 'DELETE FROM schedule_requests WHERE COURSE_ID=\''.$course_id.'\'';
			
			if(DeletePromptCommon($table))
		{	//echo 'hii'exit;
			if(BlockDelete($table))
			{
				//foreach($sql as $query)
					DBQuery($sql);
				unset($_REQUEST['modfunc']);
			}
		}
			
		}
		
		
		
			if ($course1['COURSE_PERIOD_ID']!='') {
				PopTable('header','Unable to Delete');
					DrawHeaderHome('<font color=red>Course cannot be deleted.</font>');
					echo '<div align=right><a href=Modules.php?modname=School_Setup/Courses.php&subject_id='.$subject_id.'&course_id='.$course_id.' style="text-decoration:none"><b>back to Course</b></a></div>';
					PopTable('footer');
	
			}
			else {
			if(DeletePromptCommon($table))
		{	
		//echo 'hii'exit;
			if(BlockDelete($table))
			{
				$sql[] = 'DELETE FROM courses WHERE COURSE_ID=\''.$course_id.'\'';
			#$sql[] = "UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID IN (SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID='$_REQUEST[course_id]')";
			
                       ############# query error solved	##############	
			$extra_sql='SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID=\''.$course_id.'\'';
			$result_sql = DBGet(DBQuery($extra_sql));
			$sql[] = 'UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID = \''.$result_sql.'\'';
			

                        $sql[] = 'DELETE FROM course_periods WHERE COURSE_ID=\''.$course_id.'\'';
			$sql[] = 'DELETE FROM schedule WHERE COURSE_ID=\''.$course_id.'\'';
			$sql[] = 'DELETE FROM schedule_requests WHERE COURSE_ID=\''.$course_id.'\'';
				foreach($sql as $query)
					DBQuery($query);
				unset($_REQUEST['modfunc']);
			}
		}
		}
	//if ($course['COURSE_PERIOD_ID']==''){	
	/*else {	
	
	}*/
	//}
	}
	elseif(clean_param($_REQUEST['subject_id'],PARAM_ALPHANUM))
	{
		$table = 'subject';
		$subject=DBGet(DBQuery('SELECT COURSE_ID FROM courses WHERE SUBJECT_ID=\''.$subject_id.'\''));
		foreach($subject as $subject1) 
			if ($subject1['COURSE_ID']=='') {
			$sql[] = 'DELETE FROM course_subjects WHERE SUBJECT_ID=\''.$subject_id.'\'';
			$courses = DBGet(DBQuery('SELECT COURSE_ID FROM courses WHERE SUBJECT_ID=\''.$subject_id.'\''));
			if(count($courses))
			{
				foreach($courses as $course)
				{
					$sql[] = 'DELETE FROM courses WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					#$sql[] = "UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID IN (SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID='$course[COURSE_ID]')";
					
                                        				
					$extra_sql2='SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					$result_sql2 = DBGet(DBQuery($extra_sql2));
					$sql[] = 'UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID = \''.$result_sql2.'\'';

                                        $sql[] = 'DELETE FROM course_periods WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					$sql[] = 'DELETE FROM schedule WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					$sql[] = 'DELETE FROM schedule_requests WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
				}
			}
			
			
			}
			if($subject1['COURSE_ID']!='') {
				PopTable('header','Unable to Delete');
					DrawHeaderHome('<font color=red>Field cannot be deleted.</font>');
					echo '<div align=right><a href=Modules.php?modname=School_Setup/Courses.php&subject_id='.$subject_id.' style="text-decoration:none"><b>back to Field</b></a></div>';
					PopTable('footer');
			
			}
			else {
			if(DeletePromptCommon($table))
		{	
			if(BlockDelete($table))
			{
			$sql[] = 'DELETE FROM course_subjects WHERE SUBJECT_ID=\''.$subject_id.'\'';
			$courses = DBGet(DBQuery('SELECT COURSE_ID FROM courses WHERE SUBJECT_ID=\''.$subject_id.'\''));
			if(count($courses))
			{
				foreach($courses as $course)
				{
					$sql[] = 'DELETE FROM courses WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					#$sql[] = "UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID IN (SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID='$course[COURSE_ID]')";
					
                                        				
					$extra_sql2='SELECT COURSE_PERIOD_ID FROM course_periods WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					$result_sql2 = DBGet(DBQuery($extra_sql2));
					$sql[] = 'UPDATE course_periods SET PARENT_ID=NULL WHERE PARENT_ID = \''.$result_sql2.'\'';

                                        $sql[] = 'DELETE FROM course_periods WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					$sql[] = 'DELETE FROM schedule WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					$sql[] = 'DELETE FROM schedule_requests WHERE COURSE_ID=\''.$course[COURSE_ID].'\'';
					
			
			}
	}
			foreach($sql as $query)
					DBQuery($query);
				unset($_REQUEST['modfunc']);
			}
		}
	}

}

/*if ($course1['COURSE_PERIOD_ID']=='') {
	if(DeletePrompt($table))
	{	
		if(BlockDelete($table))
		{
			foreach($sql as $query)
			echo ''
				DBQuery($query);
			unset($_REQUEST['modfunc']);
		}
	}
}*/
	/*if ($subject =='') {
	if(DeletePrompt($table))
	{
		if(BlockDelete($table))
		{
			foreach($sql as $query)
				DBQuery($query);
			unset($_REQUEST['modfunc']);
		}
	}
	}*/
	if($_REQUEST['course_period_id']) {
		if(DeletePromptCommon($table))
		{	//echo 'hii'exit;
			if(BlockDelete($table))
			{
				foreach($sql as $query)
					DBQuery($query);
				unset($_REQUEST['modfunc']);
			}
		}
	
	
	}

}

if((!$_REQUEST['modfunc'] || clean_param($_REQUEST['modfunc'],PARAM_ALPHAMOD)=='choose_course') && !$_REQUEST['course_modfunc'])
{
	if($_REQUEST['modfunc']!='choose_course')
		DrawBC("Scheduling > ".ProgramTitle());
	$sql = 'SELECT SUBJECT_ID,TITLE FROM course_subjects WHERE SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\' ORDER BY TITLE';
	$QI = DBQuery($sql);
	$subjects_RET = DBGet($QI);

	if($_REQUEST['modfunc']!='choose_course')
	{
		if(AllowEdit())
			$delete_button = "<INPUT type=button class=btn_medium value=Delete onClick='javascript:window.location=\"Modules.php?modname=$_REQUEST[modname]&modfunc=delete&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_period_id=$_REQUEST[course_period_id]\"'> ";
		// ADDING & EDITING FORM
		if(clean_param($_REQUEST['course_period_id'],PARAM_ALPHANUM))
		{
			if($_REQUEST['course_period_id']!='new')
			{
				$sql = 'SELECT PARENT_ID,TITLE,SHORT_NAME,PERIOD_ID,MON,TUE,WED,THU,FRI,SAT,SUN,PERIOD_PRACTICE_ID,MON_PRA,TUE_PRA,WED_PRA,THU_PRA,FRI_PRA,SAT_PRA,SUN_PRA,DAYS,DAYS_PRACTICE,
								MP,MARKING_PERIOD_ID,TEACHER_ID,SECONDARY_TEACHER_ID,TERTIARY_TEACHER_ID,CALENDAR_ID,
								ROOM,ROOM_PRACTICE,TOTAL_SEATS,DOES_ATTENDANCE,
								GRADE_SCALE_ID,DOES_HONOR_ROLL,DOES_CLASS_RANK,
								GENDER_RESTRICTION,HOUSE_RESTRICTION,CREDITS,
								HALF_DAY,DOES_BREAKOFF,COURSE_WEIGHT
						FROM course_periods
						WHERE COURSE_PERIOD_ID=\''.$_REQUEST[course_period_id].'\'';
				$QI = DBQuery($sql);
				$RET = DBGet($QI);
				$RET = $RET[1];
				$title = $RET['TITLE'];
				$new = false;
			}
			else
			{
				$sql = 'SELECT TITLE
						FROM courses
						WHERE COURSE_ID=\''.$_REQUEST[course_id].'\'';
				$QI = DBQuery($sql);
				$RET = DBGet($QI);
				$title = $RET[1]['TITLE'].' - New Period';
				unset($delete_button);
				unset($RET);
				$checked = 'CHECKED';
				$new = true;
			}
                 echo '<div id=cal_msg></div>';
                 echo '<div id="display_meeting_days_chk" ></div>';
			echo "<FORM name=F2 id=F2 action=Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_period_id=$_REQUEST[course_period_id] method=POST>";
                       echo '<input type="hidden" name="get_status" id="get_status" value="" />';
                       echo '<input type="hidden" name="cp_id" id="cp_id" value="'.$_REQUEST['course_period_id'].'"/>';
                DrawHeaderHome($title,$delete_button.SubmitButton('Save','','class=btn_medium onclick="return formcheck_scheduling_course_F2();"'));
			
			$header .= '<TABLE cellpadding=3 width=760 >';
			
			//ROW 1 .....................................................................................................................
			$header .= '<TR>';

			$header .= '<TD>' . TextInput($RET['SHORT_NAME'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][SHORT_NAME]','Short Name','class=cell_floating') . '</TD>';

			$teachers_RET = DBGet(DBQuery('SELECT STAFF_ID,LAST_NAME,FIRST_NAME,MIDDLE_NAME FROM staff INNER JOIN staff_school_relationship USING (staff_id) WHERE school_id=\'' . UserSchool() . '\' AND SYEAR=\'' . UserSyear() . '\' AND PROFILE=\'teacher\' AND (IS_DISABLE<>\'Y\' OR IS_DISABLE IS NULL) ORDER BY LAST_NAME,FIRST_NAME '));
			
			if(count($teachers_RET))
			{
				foreach($teachers_RET as $teacher)
					$teachers[$teacher['STAFF_ID']] = $teacher['LAST_NAME'].', '.$teacher['FIRST_NAME'].' '.$teacher['MIDDLE_NAME'];
			}
			$header .= '<TD>' . SelectInput($RET['TEACHER_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][TEACHER_ID]','Teacher',$teachers) . '</TD>';
			
			//Start Practice Teacher
			$header .= '<TD>' . SelectInput($RET['SECONDARY_TEACHER_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][SECONDARY_TEACHER_ID]','Practice Teacher 1',$teachers) . '</TD>';

			$header .= '<TD>' . SelectInput($RET['TERTIARY_TEACHER_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][TERTIARY_TEACHER_ID]','Practice Teacher 2',$teachers) . '</TD>';	
			//End Practice Teacher		
			$periods_RET = DBGet(DBQuery('SELECT PERIOD_ID,TITLE FROM school_periods WHERE SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\' ORDER BY SORT_ORDER'));
			
			
			if(count($periods_RET))
			{
				foreach($periods_RET as $period)
					$periods[$period['PERIOD_ID']] = $period['TITLE'];
			}	

			//Monday
			$header .= '<TD>' .SelectInput($RET['MON'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][MON]','Monday',$periods,'','id="MON" onchange="formcheck_periods_F2();"'). '</TD>'; 
			unset($options);
			$header .= '<TD>' .SelectInput($RET['MON_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][MON_PRA]','Pratice Monday',$periods,'','id="MON_PRA" onchange="formcheck_periods_F2();"'). '</TD>'; 
			unset($options);
				
            $header .= '</TR>';
            
			//ROW 2 .....................................................................................................................
			$header .= '<TR>';		
			//Start Room
			$header .= '<TD>' . TextInput($RET['ROOM'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][ROOM]','Room','class=cell_floating') . '</TD>';
			//End Room
			
			//Start Room Practice
			$header .= '<TD>' . TextInput($RET['ROOM_PRACTICE'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][ROOM_PRACTICE]','Room Practice','class=cell_floating') . '</TD>';
			//End Room Practice
			
			
			//Start Seat
			if($_REQUEST['course_period_id']!='new')
			{
				$available_seats = DBGet(DBQuery('SELECT (TOTAL_SEATS - FILLED_SEATS) AS AVAILABLE_SEATS FROM course_periods WHERE COURSE_PERIOD_ID=\''.$_REQUEST['course_period_id'].'\''));
				$available_seats = $available_seats[1]['AVAILABLE_SEATS'];
			}

			
			$header .= '<TD><TABLE cellpadding=0 cellspacing=0><TR>';
            $header .= '<TD>' . TextInput($RET['TOTAL_SEATS'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][TOTAL_SEATS]','Seats','size=4 class=cell_floating') . '</TD>';
			if($_REQUEST['course_period_id']!='new')
			$header .= '<TD style=padding-left:10px;><FONT color=green>' .$available_seats. '</FONT><BR><FONT color=gray><SMALL>Available Seats</SMALL></FONT></TD>';
                        $header .= '</TR></TABLE>';
                        $header .= '</TD>';
			//End Seat
			//BJJ Added to handle credits
			$header .= '<TD valign=top>' . TextInput(sprintf('%0.3f',$RET['CREDITS']),'tables[course_periods]['.$_REQUEST['course_period_id'].'][CREDITS]','Credits','size=4 class=cell_floating') . '</TD>';
			
			
			//Tuesday
			$header .= '<TD>' .SelectInput($RET['TUE'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][TUE]','Tuesday',$periods,'','id="TUE" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			$header .= '<TD>' .SelectInput($RET['TUE_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][TUE_PRA]','Pratice Tuesday',$periods,'','id="TUE_PRA" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			
			$header .= '</TR>';
            
			//ROW 3 .....................................................................................................................
			$header .= '<TR>';	

			//$header .= '<TD>' . SelectInput($RET['PERIOD_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][PERIOD_ID]','Period',$periods,'N/A','id="cp_period" onchange="formcheck_periods_F2();"') . '</TD>';
            
			$mp_RET = DBGet(DBQuery('SELECT MARKING_PERIOD_ID,SHORT_NAME,\'2\' AS t,SORT_ORDER 
				FROM school_quarters 
				WHERE SCHOOL_ID=\''.UserSchool().'\' AND SYEAR=\''.UserSyear().'\' 
			UNION SELECT MARKING_PERIOD_ID,SHORT_NAME,\'1\' AS t,SORT_ORDER 
				FROM school_semesters 
				WHERE SCHOOL_ID=\''.UserSchool().'\' 
				AND SYEAR=\''.UserSyear().'\' 
			UNION SELECT MARKING_PERIOD_ID,SHORT_NAME,\'0\' AS t,SORT_ORDER 
				FROM school_years 
				WHERE SCHOOL_ID=\''.UserSchool().'\' 
				AND SYEAR=\''.UserSyear().'\' ORDER BY 3,4'));
			
			unset($options);			
			//Start Marking Period
			if(count($mp_RET))
			{
				foreach($mp_RET as $mp)
					$options[$mp['MARKING_PERIOD_ID']] = $mp['SHORT_NAME'];
			}
			$header .= '<TD>' . SelectInput($RET['MARKING_PERIOD_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][MARKING_PERIOD_ID]','Marking Period',$options) . '</TD>';
			//End Marking Period
					
			//Start Grading Scale			
						$options_RET = DBGet(DBQuery('SELECT TITLE,ID FROM report_card_grade_scales WHERE SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\''));
			$options = array();
			foreach($options_RET as $option)
				$options[$option['ID']] = $option['TITLE'];
//			$header .= '<TD>' . SelectInput($RET['GRADE_SCALE_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][GRADE_SCALE_ID]','Grading Scale',$options,'Not Graded') . '</TD>';
                        $check_grade=DBGet(DBQuery('SELECT COUNT(1) as TOTAL FROM  gradebook_assignments ga,course_periods cp WHERE cp.COURSE_PERIOD_ID=\''.$_REQUEST['course_period_id'].'\' AND cp.COURSE_PERIOD_ID=ga.COURSE_PERIOD_ID AND  cp.SYEAR=\''.UserSyear().'\' AND cp.SCHOOL_ID=\''.UserSchool().'\' '));
                        if($check_grade[1]['TOTAL']!=0)
                        $header .= '<TD>' . SelectInput($RET['GRADE_SCALE_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][GRADE_SCALE_ID]','Grading Scale',$options,false,'id=def_grade onClick=show_this_msg("def_grade","cal_msg","grade");') . '</TD>';
                        else
                        $header .= '<TD>' . SelectInput($RET['GRADE_SCALE_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][GRADE_SCALE_ID]','Grading Scale',$options,'Not Graded') . '</TD>';
			//End Grading Scale
			
			//Start Calendar
			$options_RET = DBGet(DBQuery('SELECT TITLE,CALENDAR_ID FROM attendance_calendars WHERE SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\' ORDER BY DEFAULT_CALENDAR'));
			$options = array();
			foreach($options_RET as $option)
				$options[$option['CALENDAR_ID']] = $option['TITLE'];
                        $check_schedule=DBGet(DBQuery('SELECT COUNT(1) as TOTAL FROM schedule WHERE COURSE_PERIOD_ID=\''.$_REQUEST['course_period_id'].'\' AND (END_DATE IS NULL OR END_DATE>=\''.Date('Y-m-d').'\') AND SYEAR=\''.UserSyear().'\' AND SCHOOL_ID=\''.UserSchool().'\' '));
                        if($check_schedule[1]['TOTAL']!=0)
                        $header .= '<TD valign=top>' . SelectInput($RET['CALENDAR_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][CALENDAR_ID]','Calendar',$options,false,'id=def_cal onClick=show_this_msg("def_cal","cal_msg","calendar");') . '</TD>';
                        else
                        $header .= '<TD valign=top>' . SelectInput($RET['CALENDAR_ID'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][CALENDAR_ID]','Calendar',$options,false) . '</TD>';			
			//End Calendar
            
			//Wednesday 
			$header .= '<TD></TD>';
			$header .= '<TD>' .SelectInput($RET['WED'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][WED]','Wednesday',$periods,'','id="WED" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			$header .= '<TD>' .SelectInput($RET['WED_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][WED_PRA]','Pratice Wednesday',$periods,'','id="WED_PRA" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			
			$header .= '</TR>';
            
			//ROW 4 .....................................................................................................................
			$header .= '<TR>';			
			//$header .= '<TD valign=top>' . CheckboxInput($RET['DOES_ATTENDANCE'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][DOES_ATTENDANCE]','Takes Attendance',$checked,$new,'<IMG SRC=assets/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=assets/x.gif height=15 vspace=0 hspace=0 border=0>',true,'id="cp_does_attendance" onclick="formcheck_periods_attendance_F2(this);"') . '<br><div id="ajax_output"></div></TD>';
			$header .= '<TD valign=top>' . CheckboxInput($RET['DOES_ATTENDANCE'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][DOES_ATTENDANCE]','Takes Attendance',$checked,$new,'<IMG SRC=assets/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=assets/x.gif height=15 vspace=0 hspace=0 border=0>',true,'id=""') . '<br><div id=""></div></TD>';
			$header .='<TD></TD>';
			//$header .= '<TD valign=top>' . CheckboxInput($RET['DOES_BREAKOFF'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][DOES_BREAKOFF]','Allow Gradescale',$checked,$new,'<IMG SRC=assets/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=assets/x.gif height=15 vspace=0 hspace=0 border=0>') . '</TD>';		
            
			$header .= '<TD></TD>';			
			$header .= '<TD></TD>';
		
			//Thursday
			$header .= '<TD>' .SelectInput($RET['THU'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][THU]','Thursday',$periods,'','id="THU" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			$header .= '<TD>' .SelectInput($RET['THU_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][THU_PRA]','Pratice Thursday',$periods,'','id="THU_PRA" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			
			$header .= '</TR>';
            
			//ROW 5 .....................................................................................................................
			$header .= '<TR>';
			 $header .='<TD><input type=hidden name=tables[course_periods]['.$_REQUEST['course_period_id'].'][GENDER_RESTRICTION] value=N /></TD>';

			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
				
			//Friday
			$header .= '<TD>' .SelectInput($RET['FRI'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][FRI]','Friday',$periods,'','id="FRI" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			$header .= '<TD>' .SelectInput($RET['FRI_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][FRI_PRA]','Pratice Friday',$periods,'','id="FRI_PRA" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			
			$header .= '</TR>';
            
			//ROW 6 .....................................................................................................................
			$header .= '<TR>';			
			
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
			
			//Saturday
			$header .= '<TD>' .SelectInput($RET['SAT'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][SAT]','Saturday',$periods,'','id="SAT" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
			$header .= '<TD>' .SelectInput($RET['SAT_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][SAT_PRA]','Pratice Saturday',$periods,'','id="SAT_PRA" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);
	
			$header .= '</TR>';
            
			//ROW 7 .....................................................................................................................
			$header .= '<TR>';			
			
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
			$header .= '<TD></TD>';
						
			//Sunday
			$header .= '<TD>' .SelectInput($RET['SUN'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][SUN]','Sunday',$periods,'','id="SUN" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);	
			$header .= '<TD>' .SelectInput($RET['SUN_PRA'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][SUN_PRA]','Pratice Sunday',$periods,'','id="SUN_PRA" onchange="formcheck_periods_F2();"'). '</TD>';
			unset($options);	
			
			
			
			//END
			
			
			
			
			
			
			

			
			
			$header .= '<TR>';
                        //$header .= '<TD>' . CheckboxInput($RET['COURSE_WEIGHT'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][COURSE_WEIGHT]','Course is Weighted',$checked,$new,'<IMG SRC=assets/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=assets/x.gif height=15 vspace=0 hspace=0 border=0>') . '</TD>';
                        
                        //$header .= '<TD>' . CheckboxInput($RET['DOES_CLASS_RANK'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][DOES_CLASS_RANK]','Affects Class Rank',$checked,$new,'<IMG SRC=assets/check.gif height=15 vspace=0 hspace=0 border=0>','<IMG SRC=assets/x.gif height=15 vspace=0 hspace=0 border=0>') . '</TD>';

                        //BJJ moved parent course select here:
            if($_REQUEST['course_period_id']!='new' && $RET['PARENT_ID']!=$_REQUEST['course_period_id'])
            {
                $parent = DBGet(DBQuery('SELECT cp.TITLE as CP_TITLE,c.TITLE AS C_TITLE FROM course_periods cp,courses c WHERE c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_PERIOD_ID=\''.$RET['PARENT_ID'].'\''));
                $parent = $parent[1]['C_TITLE'].' : '.$parent[1]['CP_TITLE'];
            }
            elseif($_REQUEST['course_period_id']!='new')
            {
                $children = DBGet(DBQuery('SELECT COURSE_PERIOD_ID FROM course_periods WHERE PARENT_ID=\''.$_REQUEST['course_period_id'].'\' AND COURSE_PERIOD_ID!=\''.$_REQUEST['course_period_id'].'\''));
                if(count($children))
                    $parent = 'N/A';
                else
                    $parent = 'None';
            }

         //		--------------------------------------------- Temp Coment ------------------------------------------------- 	//
				# misc/ChooseCourse.php
		     # $header .= "<TD colspan=2><DIV id=course_div>".$parent."</DIV> ".($parent!='N/A'?"<A HREF=# onclick='window.open(\"for_window.php?modname=".$_REQUEST['modname']."&modfunc=choose_course\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'>Choose</A><BR>":'')."<small><FONT color=".Preferences('TITLES').">Parent Course Period</FONT></small></TD>";
                /*if($_REQUEST['course_period_id']!='new' && $RET['PARENT_ID']!=$_REQUEST['course_period_id']){
                    $header .= "<TD colspan=2><DIV id=course_div>".$parent."</DIV> ".($parent!='N/A' && AllowEdit()?"<A HREF=# onclick='window.open(\"for_window.php?modname=misc/ChooseParentCourse.php\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'>Choose</A>"."&nbsp;&nbsp;"."<INPUT type=checkbox name='tables[course_periods][".$_REQUEST['course_period_id']."][PARENT_ID]' value='".$_REQUEST['course_period_id']."' >&nbsp;Remove" ."<BR>":'')."<small><FONT color=".Preferences('TITLES').">Parent Course Period</FONT></small></TD>";
                }else{
                    $header .= "<TD colspan=2><DIV id=course_div>".$parent."</DIV> ".($parent!='N/A' && AllowEdit()?"<A HREF=# onclick='window.open(\"for_window.php?modname=misc/ChooseParentCourse.php\",\"\",\"scrollbars=yes,resizable=yes,width=800,height=400\");'>Choose</A><BR>":'')."<small><FONT color=".Preferences('TITLES').">Parent Course Period</FONT></small></TD>";
                }*/

		//		--------------------------------------------- Temp Coment ------------------------------------------------- 	//

			
			//BJJ Parent course select was here.

			$header .= '</TR>';


			//$header .= '<TD>' . CheckboxInput($RET['HOUSE_RESTRICTION'],'tables[course_periods]['.$_REQUEST['course_period_id'].'][HOUSE_RESTRICTION]','Restricts House','',$new) . '</TD>';
			
			
                        //BJJ added cells to place parent selection in last column.


			$header .= '</TABLE>';
			#PopTable_wo_header ('header');
			DrawHeaderHome($header);
			#PopTable ('footer');
			echo '</FORM>';
		}

		elseif(clean_param($_REQUEST['course_id'],PARAM_ALPHANUM))
		{
                                                    $grade_level_RET=  DBGet(DBQuery('SELECT ID,TITLE FROM school_gradelevels WHERE school_id=\''.UserSchool().'\''));
			if($_REQUEST['course_id']!='new')
			{
				$sql = 'SELECT c.TITLE,sg.TITLE AS GRADE_LEVEL_TITLE,c.SHORT_NAME,GRADE_LEVEL
						FROM courses c LEFT JOIN school_gradelevels sg ON c.grade_level=sg.id
						WHERE COURSE_ID=\''.$_REQUEST[course_id].'\'';
				$QI = DBQuery($sql);
				$RET = DBGet($QI);
				$RET = $RET[1];
				$title = trim($RET['TITLE'].' - '.$RET['GRADE_LEVEL_TITLE'],'- ');
			}
			else
			{
				$sql = 'SELECT TITLE
						FROM course_subjects
						WHERE SUBJECT_ID=\''.$_REQUEST[subject_id].'\' ORDER BY TITLE';
				$QI = DBQuery($sql);
				$RET = DBGet($QI);
				$title = $RET[1]['TITLE'].' - New Course';
				unset($delete_button);
				unset($RET);
			}

			echo "<FORM name=F3 id=F3 action=Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id] method=POST>";
			DrawHeaderHome($title,$delete_button.SubmitButton('Save','','class=btn_medium onclick="formcheck_scheduling_course_F3();"'));
			$header .= '<TABLE cellpadding=3 width=100%>';
			$header .= '<TR>';
                                                      foreach($grade_level_RET as $grade_level)
                                                            $grade_levels[$grade_level['ID']] = $grade_level['TITLE'];
			$header .= '<TD>' . TextInput($RET['TITLE'],'tables[courses]['.$_REQUEST['course_id'].'][TITLE]','Title','class=cell_mod_wide') . '</TD>';
			$header .= '<TD>' . TextInput($RET['SHORT_NAME'],'tables[courses]['.$_REQUEST['course_id'].'][SHORT_NAME]','Short Name','class=cell_floating') . '</TD>';
                                                      
                                                      $header .= '<TD>' . SelectInput($RET['GRADE_LEVEL'],'tables[courses]['.$_REQUEST['course_id'].'][GRADE_LEVEL]','Grade Level',$grade_levels) . '</TD>';
			if($_REQUEST['modfunc']!='choose_course')
			{
				foreach($subjects_RET as $type)
					$options[$type['SUBJECT_ID']] = $type['TITLE'];

				$header .= '<TD>' . SelectInput($RET['SUBJECT_ID']?$RET['SUBJECT_ID']:$_REQUEST['subject_id'],'tables[courses]['.$_REQUEST['course_id'].'][SUBJECT_ID]','Field',$options,false) . '</TD>';
			}
			$header .= '</TR>';
			$header .= '</TABLE>';
			DrawHeaderHome($header);
			echo '</FORM>';
		}
		elseif(clean_param($_REQUEST['subject_id'],PARAM_ALPHANUM))
		{
			if($_REQUEST['subject_id']!='new')
			{
				$sql = 'SELECT TITLE
						FROM course_subjects
						WHERE SUBJECT_ID=\''.$_REQUEST['subject_id'].'\'';
				$QI = DBQuery($sql);
				$RET = DBGet($QI);
				$RET = $RET[1];
				$title = $RET['TITLE'];
			}
			else
			{
				$title = 'New Field';
				unset($delete_button);
			}

			echo "<FORM name=F4 id=F4 action=Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id] method=POST>";
			DrawHeaderHome($title,$delete_button.SubmitButton('Save','','class=btn_medium onclick="formcheck_scheduling_course_F4();"'));
			$header .= '<TABLE cellpadding=3 width=100%>';
			$header .= '<TR>';

			$header .= '<TD>' . TextInput($RET['TITLE'],'tables[course_subjects]['.$_REQUEST['subject_id'].'][TITLE]','Title','class=cell_wide') . '</TD>';

			$header .= '</TR>';
			$header .= '</TABLE>';
			DrawHeader($header);
			echo '</FORM>';
		}
	}

	// DISPLAY THE MENU
	$LO_options = array('save'=>false,'search'=>false);

	if(!$_REQUEST['subject_id'] || clean_param($_REQUEST['modfunc'],PARAM_ALPHAMOD)=='choose_course')
		#DrawHeader('Courses');
	DrawHeaderHome('Courses',"<A HREF=Modules.php?modname=$_REQUEST[modname]&modfunc=$_REQUEST[modfunc]&course_modfunc=search>Search</A>");

	echo '<TABLE><TR>';

	if(count($subjects_RET))
	{
		if(clean_param($_REQUEST['subject_id'],PARAM_ALPHANUM))
		{
			foreach($subjects_RET as $key=>$value)
			{
				if($value['SUBJECT_ID']==$_REQUEST['subject_id'])
					$subjects_RET[$key]['row_color'] = Preferences('HIGHLIGHT');
			}
		}
	}

	echo '<TD valign=top>';
	$columns = array('TITLE'=>'Field');
	$link = array();
	$link['TITLE']['link'] = "Modules.php?modname=$_REQUEST[modname]";
	//$link['TITLE']['link'] = "#"." onclick='check_content(\"ajax.php?modname=$_REQUEST[modname]\");'";
	$link['TITLE']['variables'] = array('subject_id'=>'SUBJECT_ID');
	if($_REQUEST['modfunc']!='choose_course')
		$link['add']['link'] = "Modules.php?modname=$_REQUEST[modname]&subject_id=new";
		//$link['add']['link'] = "#"." onclick='check_content(\"ajax.php?modname=$_REQUEST[modname]&subject_id=new\");'";
	else
		$link['TITLE']['link'] .= "&modfunc=$_REQUEST[modfunc]";

	ListOutput($subjects_RET,$columns,'Field','Fields',$link,array(),$LO_options);
	echo '</TD>';

	if(clean_param($_REQUEST['subject_id'],PARAM_ALPHANUM) && $_REQUEST['subject_id']!='new')
	{
		$sql = 'SELECT COURSE_ID,c.TITLE, CONCAT_WS(\' - \',c.title,sg.title) AS GRADE_COURSE FROM courses c LEFT JOIN school_gradelevels sg ON c.grade_level=sg.id WHERE SUBJECT_ID=\''.$_REQUEST['subject_id'].'\' ORDER BY c.TITLE';
		$QI = DBQuery($sql);
		$courses_RET = DBGet($QI);

		if(count($courses_RET))
		{
			if(clean_param($_REQUEST['course_id'],PARAM_ALPHANUM))
			{
				foreach($courses_RET as $key=>$value)
				{
					if($value['COURSE_ID']==$_REQUEST['course_id'])
						$courses_RET[$key]['row_color'] = Preferences('HIGHLIGHT');
				}
			}
		}

		echo '<TD valign=top>';
		$columns = array('GRADE_COURSE'=>'Course');
		$link = array();
		$link['GRADE_COURSE']['link'] = "Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]";
		//$link['TITLE']['link'] = "#"." onclick='check_content(\"ajax.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]\");'";
		$link['GRADE_COURSE']['variables'] = array('course_id'=>'COURSE_ID');
		if($_REQUEST['modfunc']!='choose_course')
			$link['add']['link'] = "Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=new";
			//$link['add']['link'] = "#"." onclick='check_content(\"ajax.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=new\");'";
		else
			$link['GRADE_COURSE']['link'] .= "&modfunc=$_REQUEST[modfunc]";

		ListOutput($courses_RET,$columns,'Course','Courses',$link,array(),$LO_options);
		echo '</TD>';

		if(clean_param($_REQUEST['course_id'],PARAM_ALPHANUM) && $_REQUEST['course_id']!='new')
		{

                #$sql = "SELECT COURSE_PERIOD_ID,TITLE,COALESCE(TOTAL_SEATS-FILLED_SEATS,0) AS AVAILABLE_SEATS FROM course_periods WHERE COURSE_ID='$_REQUEST[course_id]' ORDER BY TITLE";
				
				
				$sql_mp_filter = 'SELECT MP_TYPE, PARENT_ID, GRANDPARENT_ID FROM marking_periods WHERE MARKING_PERIOD_ID='.UserMP();
				$res_mp_filter = DBQuery($sql_mp_filter);
                $row_mp_filter = DBGet($res_mp_filter);
				
				$mp_type = $row_mp_filter[1]['MP_TYPE'];
				$p_id = $row_mp_filter[1]['PARENT_ID'];
				$gp_id = $row_mp_filter[1]['GRANDPARENT_ID'];
				
				if($mp_type == 'quarter')
				{
					$cond = ' AND (MARKING_PERIOD_ID = '.UserMP().' OR MARKING_PERIOD_ID = '.$p_id.' OR MARKING_PERIOD_ID = '.$gp_id.')';
				}
				if($mp_type == 'semester')
				{
					$cond = ' AND (MARKING_PERIOD_ID = '.UserMP().' OR MARKING_PERIOD_ID = '.$p_id.')';
				}
				if($mp_type == 'year')
				{
					$cond = ' AND MARKING_PERIOD_ID = '.UserMP();
				}
				
				
				$sql = 'SELECT COURSE_PERIOD_ID,TITLE,COALESCE(TOTAL_SEATS-FILLED_SEATS,0) AS AVAILABLE_SEATS FROM course_periods WHERE COURSE_ID=\''.$_REQUEST[course_id].'\''.$cond.' ORDER BY TITLE';
				
                $QI = DBQuery($sql);
                $periods_RET = DBGet($QI);

                if(count($periods_RET))
                {
                    if(clean_param($_REQUEST['course_period_id'],PARAM_ALPHANUM))
                    {
                        foreach($periods_RET as $key=>$value)
                        {
                            if($value['COURSE_PERIOD_ID']==$_REQUEST['course_period_id'])
                                $periods_RET[$key]['row_color'] = Preferences('HIGHLIGHT');
                        }
                    }
                }

                echo '<TD valign=top>';
                $columns = array('TITLE'=>'Course Period');
                if($_REQUEST['modname']=='Scheduling/Schedule.php')
                    $columns += array('AVAILABLE_SEATS'=>'Available Seats');
                $link = array();
                $link['TITLE']['link'] = "Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]";
				//$link['TITLE']['link'] = "#"." onclick='check_content(\"ajax.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]\");'";
                $link['TITLE']['variables'] = array('course_period_id'=>'COURSE_PERIOD_ID');
                if($_REQUEST['modfunc']!='choose_course')
                    $link['add']['link'] = "Modules.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_period_id=new";
					//$link['add']['link'] = "#"." onclick='check_content(\"ajax.php?modname=$_REQUEST[modname]&subject_id=$_REQUEST[subject_id]&course_id=$_REQUEST[course_id]&course_period_id=new\");'";
                else
                    $link['TITLE']['link'] .= "&modfunc=$_REQUEST[modfunc]";

                ListOutput($periods_RET,$columns,'Period','Periods',$link,array(),$LO_options);
                echo '</TD>';
            
		}
	}

	echo '</TR></TABLE>';
}

if(clean_param($_REQUEST['modname'],PARAM_ALPHAEXT)=='Scheduling/Courses.php' && clean_param($_REQUEST['modfunc'],PARAM_ALPHAMOD)=='choose_course' && clean_param($_REQUEST['course_period_id'],PARAM_ALPHANUM))
{
	$course_title = DBGet(DBQuery("SELECT TITLE FROM course_periods WHERE COURSE_PERIOD_ID='".$_REQUEST['course_period_id']."'"));
	$course_title = $course_title[1]['TITLE'] . '<INPUT type=hidden name=tables[parent_id] value='.$_REQUEST['course_period_id'].'>';

	echo "<script language=javascript>opener.document.getElementById(\"course_div\").innerHTML = \"$course_title</small>\"; window.close();</script>";
}


?>
